昨天刷 Codewars Lv8 題目
覺得不過癮
這次改以 TDD 刷 Codewars Lv7 題目
花了些時間講解如何設定 snippet 及 RSpec
snippet 做得好,省時又省力外,還能避免常打的語法打錯字
RSpec 寫得好,生活沒煩惱 XD
題目:
Complete the function that accepts a string parameter, and reverses each word in the string. All spaces in the string should be retained.
Examples
"This is an example!" ==> "sihT si na !elpmaxe"
"double spaces" ==> "elbuod secaps"
def reverse_words(str)
# Go for it
end
Sample Tests:
Test.assert_equals(reverse_words('The quick brown fox jumps over the lazy dog.'), 'ehT kciuq nworb xof spmuj revo eht yzal .god')
Test.assert_equals(reverse_words('apple'), 'elppa')
Test.assert_equals(reverse_words('a b c d'), 'a b c d')
Test.assert_equals(reverse_words('double spaced words'), 'elbuod decaps sdrow')
解題:
def reverse_words(str)
return str.split.map{ |x| x.reverse }.join' ' if str.scan(/ /) == []
str.split.map{ |x| x.reverse }.join' '
end
本文同步發布於 小菜的 Blog https://riverye.com/